var Soc   = require('faye-websocket'),
	EventSource = Soc.EventSource,
    http        = require('http');
var server = http.createServer(function(req, res){
	process.env.HUBOT_REST_SEND_URL = 'http://172.17.17.67:3000/adapter_back/';
});
var wsArray = {};

module.exports = class WebSocket{
	init(port, receviceCallBackFunc){
		server.on('upgrade', function(request, socket, body) {
			if (Soc.isWebSocket(request)) {
		    	var ws = new Soc(request, socket, body);
		    	var room = Date.now();//TODO: 暂时通过时间戳来创建房间号，后续可以采用更好的方式，避免冲突
		    	wsArray[room] = ws;
		    	ws.on('message', function(event) { 
		    		console.log(event.data);
		    		receviceCallBackFunc(room,event.data);
		    	});

			    ws.on('close', function(event) {
			    	console.log('close', event.code, event.reason);
			    	ws = null;
			    });
		  	}
		});
		server.listen(port);
		console.log('websocket started at port ' + port + '...');
	}
	send(room, message){
		var ws = wsArray[room];
		ws.send(message);
	}
}